﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NoteHelper.Utils
{
    public class ModelMapperBuilder
    {
        [Description("命名空间")]
        public string ModelNameSpace { get; set; }

        [Description("文件输出路径")]
        public string OutputPath { get; set; }

        public Type ModelType { get; set; }

        public void GenerateMapFile()
        {
            var mapperFile = System.IO.Path.Combine(OutputPath, string.Format("{0}.cs", ModelType.Name));
            var xmlContext = BuilderXmlContent();
            IOHelper.WriteFile(mapperFile, xmlContext);
        }

        private string BuilderXmlContent()
        {
            var ctx = new StringBuilder();
            ctx.Append("<?xml version=\"1.0\" encoding=\"utf - 8\" ?>\r\n");
            ctx.AppendFormat("<sqlMap namespace=\"{0}\"", ModelNameSpace);
            ctx.Append(" xmlns=\"http://ibatis.apache.org/mapping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" >\r\n");
            ctx.Append("<alias>\r\n");
            ctx.AppendFormat("<typeAlias alias=\"{0}\" type=\"{1}\" />\r\n", ModelType.Name, ModelType.FullName);
            ctx.Append("</alias>\r\n");

            ctx.Append("<cacheModels>\r\n");
            ctx.AppendFormat(" <cacheModel id = \"{0}Cache\" implementation = \"LRU\" >\r\n", ModelType.Name);
            ctx.Append("<flushInterval hours = \"24\" />\r\n");
            ctx.Append("<property name = \"CacheSize\" value = \"1000\" />\r\n");
            ctx.Append("</cacheModel >\r\n");
            ctx.Append("</cacheModels >\r\n");

            ctx.Append("  <resultMaps>\r\n");
            ctx.AppendFormat(" <resultMap id = \"{0}Result\" class=\"{0}\">\r\n", ModelType.Name);
            foreach (var propertyInfo in ModelType.GetProperties())
            {
                ctx.AppendFormat("<result property = \"{0}\" column = \"{0}\" /> ", propertyInfo.Name);
            }
            ctx.Append("    </resultMap>\r\n  </ resultMaps >\r\n ");



            return ctx.ToString();
        }
    }
}
